package ${package}.advice;

import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.RequestAttributes;

import ${package}.exception.BusinessException;


@org.springframework.web.bind.annotation.ControllerAdvice
public class ControllerAdvice {

    public static final Logger LOGGER = LoggerFactory.getLogger(ControllerAdvice.class);

    @Autowired
    private TrackIdHolder trackIdHolder;

    @ExceptionHandler(value = Exception.class)
    public void handleException(Exception e, HttpServletResponse response) throws Exception {
        LOGGER.error(e.getMessage(), e);
        if (e instanceof BusinessException) {
            BusinessException businessException = (BusinessException) e;
            response.sendError(businessException.getHttpStatusCode(), businessException.getMessage());
        } else if (e instanceof IllegalArgumentException) {
            IllegalArgumentException illegalArgumentException = (IllegalArgumentException) e;
            response.sendError(HttpStatus.BAD_REQUEST.value(), "参数错误" + illegalArgumentException.getMessage());
        } else {
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务器内部出错");
        }
    }

    /**
     * 修改自定义异常返回
     *
     * @return
     */
    @Bean
    public ErrorAttributes errorAttributes() {
        return new DefaultErrorAttributes() {
            @Override
            public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
                Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
                errorAttributes.put("trackNo", trackIdHolder.getTrackId());
                errorAttributes.remove("exception");
                return errorAttributes;
            }
        };
    }

    //    {
    //        "timestamp": 1413883870237,
    //            "status": 500,
    //            "error": "Internal Server Error",
    //            "exception": "org.example.ServiceException",
    //            "message": "somthing goes wrong",
    //            "path": "/index"
    //    }
}
